package com.yxinsur.imc.business.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxinsur.imc.business.domain.ImcBroker;
import com.yxinsur.imc.business.domain.ImcTeam;
import com.yxinsur.imc.business.events.publisher.TeamCreateEventPublisher;
import com.yxinsur.imc.business.excel.TeamTemplate;
import com.yxinsur.imc.business.form.TeamForm;
import com.yxinsur.imc.business.mapper.ImcBrokerMapper;
import com.yxinsur.imc.business.mapper.ImcTeamMapper;
import com.yxinsur.imc.business.service.IImcTeamService;
import com.yxinsur.imc.business.vo.TeamVo;
import com.yxinsur.imc.common.core.domain.entity.SysOrg;
import com.yxinsur.imc.common.exception.BusinessException;
import com.yxinsur.imc.common.exception.CustomException;
import com.yxinsur.imc.common.utils.DateUtils;
import com.yxinsur.imc.common.utils.SecurityUtils;
import com.yxinsur.imc.common.utils.StringUtils;
import com.yxinsur.imc.system.mapper.SysOrgMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


/**
 * 营销区-团队Service业务层处理
 *
 * @author imc
 * @date 2021-03-23
 */
@Service
public class ImcTeamServiceImpl extends ServiceImpl<ImcTeamMapper, ImcTeam> implements IImcTeamService {
    @Autowired
    private ImcTeamMapper imcTeamMapper;
    @Autowired
    private ImcBrokerMapper imcBrokerMapper;
    @Autowired
    private SysOrgMapper sysOrgMapper;
    @Autowired
    private TeamCreateEventPublisher teamCreateEventPublisher;

    /**
     * 查询营销区-团队
     *
     * @param id 营销区-团队ID
     * @return 营销区-团队
     */
    @Override
    public ImcTeam selectImcTeamById(Long id) {
        ImcTeam imcTeam = imcTeamMapper.selectImcTeamById(id);
        imcTeam.setParentId(null);
        return imcTeam;
    }

    /**
     * 查询营销区-团队列表
     *
     * @param teamForm 营销区-团队
     * @return 营销区-团队
     */
    @Override
    public List<TeamVo> selectImcTeamList(TeamForm teamForm) {
        teamForm.setTenantId(SecurityUtils.getTenantId());
        teamForm.setParentId(0L);
        List<TeamVo> teamVos = imcTeamMapper.selectImcTeamList(teamForm);
        for (TeamVo teamVo : teamVos) {
            if(0==teamVo.getParentId()){
               teamVo.setParentId(null);
            }
            ImcBroker imcBroker = imcBrokerMapper.selectImcBrokerById(String.valueOf(teamVo.getTeamLeaderId()));
            //负责人非必填
            if(!StringUtils.isNull(imcBroker)){
                teamVo.setTeamLeaderName(imcBroker.getFullName());
                teamVo.setTeamLeaderCode(imcBroker.getBrokerCode());
            }
            SysOrg sysOrg = sysOrgMapper.selectOrgById(teamVo.getOrgId());
            teamVo.setOrgName(sysOrg.getOrgName());
            teamVo.setTeamChildrenList(createTreeTeam(teamVo));
        }
        return teamVos;
    }

    /**
     * 根节点 team
     * @param team
     * @return
     */
    private ArrayList<TeamVo> createTreeTeam(TeamVo team) {
        //获得根节点team 递归查询
        List<TeamVo> imcChildrenTeams = imcTeamMapper.selectImcTeamByParentId(team.getId());
        if (CollectionUtils.isEmpty(imcChildrenTeams)) {
            return new ArrayList<TeamVo>();
        }
        ArrayList<TeamVo> teamVos = new ArrayList<>();
        for (TeamVo imcTeam : imcChildrenTeams) {
            TeamVo teamVo = new TeamVo();
            BeanUtils.copyProperties(imcTeam, teamVo);
            teamVo.setParentName(team.getTeamName());
            ImcBroker imcBroker = imcBrokerMapper.selectImcBrokerById(String.valueOf(imcTeam.getTeamLeaderId()));
            if(!StringUtils.isNull(imcBroker)){
                teamVo.setTeamLeaderName(imcBroker.getFullName());
                teamVo.setTeamLeaderCode(imcBroker.getBrokerCode());
            }
            SysOrg sysOrg = sysOrgMapper.selectOrgById(imcTeam.getOrgId());
            teamVo.setOrgName(sysOrg.getOrgName());
            teamVo.setTeamChildrenList(createTreeTeam(imcTeam));
            teamVos.add(teamVo);
        }
        return teamVos;
    }

    /**
     * 新增营销区-团队
     *
     * @param teamForm 营销区-团队
     * @return 结果
     */
    @Override
    public int insertImcTeam(TeamForm teamForm) {
        ImcTeam imcTeam = new ImcTeam();
        ImcTeam team = imcTeamMapper.selectByTeamName(teamForm.getTeamName(),SecurityUtils.getTenantId());
        if(team!=null){
            throw new BusinessException("租户下存在该团队名称，请检查");
        }
        SysOrg sysOrg = sysOrgMapper.selectOrgById(teamForm.getOrgId());
        int orgRank = sysOrg.getAncestors().length() - sysOrg.getAncestors().replace(",","").length();
        if(orgRank<2){
            throw new BusinessException("团队所属机构只能为三级机构");
        }
        BeanUtils.copyProperties(teamForm, imcTeam);
        Long parentId = teamForm.getParentId();
        ImcTeam imcTeamById = imcTeamMapper.selectImcTeamById(parentId);
        if (StringUtils.isNull(imcTeamById)) {
            imcTeam.setParentId(0L);
            imcTeam.setAncestors("0");
        } else {
            imcTeam.setAncestors(imcTeamById.getAncestors() + "," + parentId);
        }
        imcTeam.setCreateId(SecurityUtils.getUsername());
        imcTeam.setUpdateId(SecurityUtils.getUsername());
        imcTeam.setTenantId(SecurityUtils.getTenantId());
        imcTeamMapper.insertImcTeam(imcTeam);
        teamCreateEventPublisher.pushlish("团队信息录入成功", imcTeam);
        return 1;
    }

    /**
     * 修改营销区-团队
     *
     * @param teamForm 营销区-团队
     * @return 结果
     */
    @Override
    @Transactional
    public int updateImcTeam(TeamForm teamForm) {
        try {
            ImcTeam imcTeam = new ImcTeam();
            BeanUtils.copyProperties(teamForm, imcTeam);
            Long parentId = teamForm.getParentId();
            ImcTeam imcTeamById = imcTeamMapper.selectImcTeamById(parentId);
            String oldAncestors = imcTeam.getAncestors();
            String newAncestors = "";
            if (StringUtils.isNull(imcTeamById)) {
                imcTeam.setAncestors("0");
                imcTeam.setParentId(0L);
                newAncestors = "0,"+imcTeam.getId();
            } else {
                //祖籍列表包含自己提示错误信息
                List<String> ancestors = Arrays.asList(imcTeamById.getAncestors().split(","));
                if(ancestors.contains(String.valueOf(imcTeam.getId())) ||  imcTeam.getId().equals(imcTeamById.getId())){
                    throw new BusinessException("上级团队不能包含自己及以下团队");
                }
                imcTeam.setAncestors(imcTeamById.getAncestors() + "," + parentId);
                newAncestors=imcTeam.getAncestors()+","+imcTeam.getId();
            }

            //修改所辖团队祖籍列表
            updateImcTeamChild(oldAncestors+","+imcTeam.getId(),newAncestors);
            imcTeam.setCreateId(SecurityUtils.getUsername());
            imcTeam.setUpdateId(SecurityUtils.getUsername());
            imcTeam.setTenantId(SecurityUtils.getTenantId());
            imcTeamMapper.updateImcTeam(imcTeam);
            teamCreateEventPublisher.pushlish("团队信息录入成功", imcTeam);
        } catch (Exception e) {
            throw new BusinessException("保存团队信息异常:"+e.getMessage());
        }
        return 1;
    }

    /**
     * 团队修改子团队的祖籍信息
     * @param oldAncestors
     * @param newAncestors
     */
    private void updateImcTeamChild(String oldAncestors,String newAncestors) {
        List<ImcTeam> imcTeamChildren = imcTeamMapper.selectImcTeamChild(oldAncestors);
        for (ImcTeam imcTeamChild : imcTeamChildren) {
            imcTeamChild.setAncestors(imcTeamChild.getAncestors().replace(oldAncestors,newAncestors));
            imcTeamMapper.updateImcTeam(imcTeamChild);
        }
    }

    /**
     * 批量删除营销区-团队
     *
     * @param ids 需要删除的营销区-团队ID
     * @return 结果
     */
    @Override
    public int deleteImcTeamByIds(String[] ids) {
        return imcTeamMapper.deleteImcTeamByIds(ids);
    }

    /**
     * 删除营销区-团队信息
     *
     * @param id 营销区-团队ID
     * @return 结果
     */
    @Override
    public int deleteImcTeamById(String id) {
        return imcTeamMapper.deleteImcTeamById(id);
    }

    @Override
    public HashMap<String, Object> checkImportTeam(List<TeamTemplate> imcTeamList) {
        HashMap<String, Object> returnMap = new HashMap<>();
        returnMap.put("flag", true);
        if (StringUtils.isNull(imcTeamList) || imcTeamList.size() == 0) {
            returnMap.put("flag", false);
            returnMap.put("message", "导入团队信息不能为空");
        }
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (TeamTemplate imcTeam : imcTeamList) {
            QueryWrapper<ImcTeam> wrapper = new QueryWrapper<>();
            if(StringUtils.isEmpty(imcTeam.getTeamName())){
                failureNum++;
                returnMap.put("flag",false);
                failureMsg.append("<br/>" + failureNum + "、团队名称不能为空");
                returnMap.put("message",failureMsg.toString());
            } else {
                wrapper.eq("team_name", imcTeam.getTeamName());
                wrapper.eq("tenant_id",SecurityUtils.getTenantId());
                ImcTeam team = imcTeamMapper.selectOne(wrapper);
                if (!StringUtils.isNull(team)) {
                    failureNum++;
                    returnMap.put("flag", false);
                    failureMsg.append("<br/>" + failureNum + "、团队信息 " + imcTeam.getTeamName() + "团队名称已存在");
                    returnMap.put("message", failureMsg.toString());
                }
            }

            //管理机构不能为空   当前租户下的机构
            if(StringUtils.isEmpty(imcTeam.getOrgName())){
                failureNum++;
                returnMap.put("flag",false);
                failureMsg.append("<br/>" + failureNum + "、团队信息"+imcTeam.getTeamName()+" 机构名称不能为空");
                returnMap.put("message",failureMsg.toString());
            }else{
                SysOrg sysOrg = sysOrgMapper.selectOrgByOrgName(imcTeam.getOrgName(),SecurityUtils.getTenantId());
                if(StringUtils.isNull(sysOrg)){
                    failureNum++;
                    returnMap.put("flag",false);
                    failureMsg.append("<br/>" + failureNum + "、团队信息"+imcTeam.getTeamName()+"所在租户下该机构不存在");
                    returnMap.put("message",failureMsg.toString());
                }
            }
        }

        return returnMap;

    }

    @Override
    public String importTeam(List<TeamTemplate> imcTeamList, boolean updateSupport, String operName) {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TeamTemplate teamTemplate : imcTeamList) {
            try {
                ImcTeam imcTeam = new ImcTeam();
                String orgName = teamTemplate.getOrgName();
                SysOrg sysOrg = sysOrgMapper.selectOrgByOrgName(orgName, SecurityUtils.getTenantId());
                imcTeam.setOrgId(sysOrg.getOrgId());
                BeanUtils.copyProperties(teamTemplate,imcTeam);
                successNum++;
                imcTeam.setParentId(0L);
                imcTeam.setAncestors("0");
                imcTeam.setTenantId(SecurityUtils.getTenantId());
                imcTeamMapper.insertImcTeam(imcTeam);
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、团队信息 " + teamTemplate.getTeamName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            //保存团队信息
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<TeamVo> selectExportImcTeamList(TeamForm teamForm) {
        List<TeamVo> teamVos = selectImcTeamList(teamForm);
        List<TeamVo> result= tree2list(teamVos);
        return result;

    }

    /**
     * 删除营销团队
     * @param id
     * @return
     */
    @Override
    public int deleteTeam(Long id) {
        ImcTeam imcTeam = imcTeamMapper.selectImcTeamById(id);
        imcTeam.setTeamName(imcTeam.getTeamName()+"-废弃");
        imcTeam.setIsDeleted(id.toString());
        return imcTeamMapper.updateImcTeam(imcTeam);
    }

    private List<TeamVo> tree2list(List<TeamVo> teamVos) {
        ArrayList<TeamVo> result = new ArrayList<>();
        for (TeamVo teamVo : teamVos) {
            List<TeamVo> teamChildrenList = teamVo.getTeamChildrenList();
            result.add(teamVo);
            if(!CollectionUtils.isEmpty(teamChildrenList)){
                result.addAll(tree2list(teamChildrenList));
                teamVo.setTeamChildrenList(null);
            }
        }
        return result;
    }
}
